<template>
    <view class="content">
        <view class="box">
            <view class="item">
                <view class="title">公告标题</view>
                <textarea v-model="title" placeholder="请输入标题" class="tit-t" :auto-height="true"></textarea>
            </view>
            <view class="item">
                <view class="title">公告详情</view>
                <textarea v-model="content" placeholder="请输入详情" maxlength="-1"></textarea>
            </view>
            <view class="item">
                <view class="title">公告封面</view>
                <view class="img-box" @click="chooseImg(1)">
                    <image :src="coverUrl" class="up-photo" v-if="coverUrl"></image>
                    <image src="../../static/images/up_photo.png" class="up-photo" v-else></image>
                </view>
            </view>
            <view class="item">
                <view class="title">公告配图（最多可上传9张）</view>
                <!-- <tnWaterMater @pBackImage="backImage" ref="childWaterMater"></tnWaterMater> -->
                
                <view class="img-box">
                    <view class="img-box-item" v-for="(item, index) in imgUrl" :key="index" v-if="imgUrl.length">
                        <image :src="item" class="up-img" @click="doPreview(item)"></image>
                        <view class="del-img" @click="delImg(index)">删除</view>
                    </view>
                    <image src="../../static/images/up_photo.png" class="up-img" v-if="imgUrl.length < 9" @click="chooseImg(2)"></image>
                </view>
            </view>
        </view>
        <view v-show="show">
            <canvas canvas-id="Canvas" id="Canvas"></canvas>
        </view>
        <view class="btn" @click="doSubmit">立即添加</view>
    </view>
</template>

<script>
    import tnWaterMark from "@/components/tn-waterMark/index.vue"
    // import tnWaterMark from "../../../components/tn-waterMark/index.vue"
    import { API_URL } from '@/static/js/common.js';
    export default {
        components: { tnWaterMark },
        data() {
            return {
                show: true,
                URL: API_URL, //上传图片用的
                coverUrl: '',
                coverId: '',
                imgUrl: [],//图片
                imgId: [],//图片id
                title: '',
                content: '',
                photoData: [],
                context: '',
                width: '',
                height: '',
                url: '',
            };
        },
        onLoad() {
            uni.$on('pBackImage', data => {
                console.log(data)
                this.backImage(data)
            })
        },
        onShow() {
            
        },
        methods: {
            doSubmit() {
                if (!this.title) {
                    this.$toast('请输入标题');
                    return
                }
                if (!this.content) {
                    this.$toast('请输入详情');
                    return
                }
                if (!this.coverId) {
                    this.$toast('请上传公告封面图');
                    return
                }
                this.$ajax('notice_submit', {
                	user_token: this.$getSync('userToken'),
                    title: this.title,//标题
                    notice: this.content,//公告详情
                    image_id: this.coverId,//封面图id
                    images: this.imgId.join(','),//配图id，分割字符串
                    id: '',//编辑 公告id
                }).then(ret => {
                	if (ret.success == 1000) {
                		this.$toast('添加成功');
                        setTimeout(() => {
                            this.$backT()
                        }, 300)
                	} else {
                		this.$toast(ret.msg);
                	}
                });
            },
            
            // selectImg(){
            //     let _this = this;
            //     uni.chooseImage({
            //         count: 1, //默认9
            //         sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
            //         sourceType: ['album'], //从相册选择
            //         success: function(res) {
            //             console.log(res)
            //             // _this.photoData = [plus.io.convertLocalFileSystemURL(res.tempFilePaths[0])]
            //             _this.photoData = [res.tempFilePaths[0]]
            //         },
            //         fail(res) {

            //         }
            //     });
            // },
            
            // backImage(data){
            //     console.log(data.length);
            //     // this.imgUrl.push(data);
            //     this.photoData.push(data);
            // },
            // addWaterBase64(){
            //     let _this = this;
            //     let model = {};
            //     model.url = _this.photoData[0];
            //     // model.maxSize = 100;
            //     model.watermark = [
            //         {
            //             type: 'image',
            //             path: '/static/icon/add_03.png',
            //             x: -500,
            //             y: -500,
            //             width: 20,
            //             height: 20,
            //             rotate: 25,
            //             textAlign: 'top',
            //             textBaseline: 'top',
            //             repeatWidth: 1500,
            //             repeatHeight: 2000,
            //             isRepeat: true
            //         },
            //         {
            //             type: 'text',
            //             fillStyle: 'rgba(250, 250, 250, 1)',
            //             content: '我是水印哈哈哈',
            //             font: '6px',
            //             x: -500,
            //             y: -500,
            //             shadowColor: 'rgba(0, 0, 0, 1)',
            //             shadowOffsetX: 2,
            //             shadowOffsetY: 2,
            //             rotate: 25,
            //             repeatWidth: 1500,
            //             repeatHeight: 2000,
            //             isRepeat: true
            //         }
            //     ];
            //     console.log(this.$refs)
            //     setTimeout(() => {
            //         console.log(_this.$refs.childWaterMater)
            //         _this.$refs.childWaterMater.addWaterMark(model);
            //     }, 1000)
            //     // _this.$nextTick(()=>{
            //     // 	console.log(_this.$refs.childWaterMater)
            //     // 	_this.$refs.childWaterMater.addWaterMark(model);
            //     // })
            // },
            // 上传图片
            chooseImg(num) {
                var _this = this;
                var context = uni.createCanvasContext('Canvas', this)
                uni.chooseImage({
                    count: 9, //默认9
                    sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
                    sourceType: ['album', 'camera'], // 相机拍照 album 相册、camera 拍照
                    success: (res) => {
                        console.log('res',res)
                        var file = res.tempFilePaths[0];
                        const tempFiles = res.tempFiles[0]
                        
                        uni.getImageInfo({
                        	src: res.tempFilePaths[0],
                        	success: function(image) {
                                console.log('image',image)
                        		_this.width = image.width + 'px'
                        		_this.height = image.height + 'px'
                        		setTimeout(function() {
                                    context.width = _this.width;
                                    context.height = _this.height;
                                    context.fillRect(0, 0, _this.width, _this.height);
                                    // 将图片src放到cancas内，宽高为图片大小
                                    context.drawImage(res.tempFilePaths[0], 0, 0, image.width, image.height)
                                                
                                    context.rotate(45 * Math.PI / 180);
                                    for (let i = 0; i <= 50; i++) {
                                        context.beginPath();
                                        context.setFontSize(50);
                                        context.setFillStyle("rgba(169,169,169,0.4)");
                                        context.fillText("我是水印", 0, i * 170);
                                        for (let j = 0; j <= 50; j++) {
                                            context.beginPath();
                                            context.setFontSize(50);
                                            context.setFillStyle("rgba(169,169,169,0.4)");
                                            context.fillText("我是水印", j * 340, i * 170);
                                        }
                                    }
                                    for (let i = 0; i < 50; i++) {
                                        context.beginPath();
                                        context.setFontSize(50);
                                        context.setFillStyle("rgba(169,169,169,0.4)");
                                        context.fillText("我是水印", 0, -170 * i);
                                        for (let j = 1; j < 50; j++) {
                                            context.beginPath();
                                            context.setFontSize(50);
                                            context.setFillStyle("rgba(169,169,169,0.4)");
                                            context.fillText("我是水印", 340 * j, -170 * i);
                                        }
                                    }
                                    // context.rotate(-45 * Math.PI / 180);
                                    // uni.showLoading({title: '上传中...',})
                                    context.draw(false, () => {
                                        console.log('11111111')
                                        setTimeout(() => {
                                            uni.canvasToTempFilePath({
                                                canvasId: "Canvas",
                                                fileType: 'jpg' || 'jpeg',
                                                success: (path) => {
                                                    //压缩
                                                    console.log('path',path)
                                                    uni.compressImage({
                                                        src: path.tempFilePath,
                                                        quality: 20,
                                                        success: res => {
                                                            _this.url = res.tempFilePath + '.jpg'
                                                            console.log('uni.compressImage',res,_this.url)
                                                        }
                                                    })
                                                }
                                            }, this)
                                        }, 500)
                                    })
                            }, 1000)
                        }
                    })
                        
                        
                        
                        
                        // this.photoData = [plus.io.convertLocalFileSystemURL(res.tempFilePaths[0])]
                        // this.photoData = [res.tempFilePaths[0]]
                        // this.addWaterBase64()
                        
                        // const tempFilePaths = res.tempFilePaths;
                        // for (let i = 0; i < tempFilePaths.length; i++) {
                        //     uni.uploadFile({
                        //         url: this.URL + 'api/upload_image', //仅为示例，并非真实接口地址。
                        //         filePath: res.tempFilePaths[i],
                        //         name: 'image',
                        //         formData:{
                        //             module: 'api'
                        //         },
                        //         success: result => {
                        //             console.log(result)
                        //             let data = JSON.parse(result.data).detail; //后台返回的路径data.attach_uri
                        //             if (num == 1) {
                        //                 this.coverUrl = data.image
                        //                 this.coverId = data.image_id
                        //             } else {
                        //                 this.imgUrl.push(data.image);
                        //                 this.imgId.push(data.image_id);
                        //             }
                        //         }
                        //     });
                        // }
                    }
                });
            },
            uploadImg() {
                let _this = this
                uni.uploadFile({
                    url: _this.URL + 'api/upload_image', //仅为示例，并非真实接口地址。
                    filePath: _this.url,
                    name: 'image',
                    formData:{
                        module: 'api'
                    },
                    success: result => {
                        console.log(result)
                        let data = JSON.parse(result.data).detail; //后台返回的路径data.attach_uri
                        if (num == 1) {
                            _this.coverUrl = data.image
                            _this.coverId = data.image_id
                        } else {
                            _this.imgUrl.push(data.image);
                            _this.imgId.push(data.image_id);
                        }
                    }
                });
            },
            // 预览图片
            doPreview(item) {
            	var arr = [];
            	arr.push(item);
            	uni.previewImage({
            	    urls: arr,
            	    longPressActions: {
            	        success: function(data) {
            	        },
            	        fail: function(err) {
                            console.log(err)
            	        }
            	    }
            	});
            },
            //删除
            delImg(index) {
                uni.showModal({
                    title: '提示',
                    content: '确定要删除吗？',
                    success: res => {
                        if (res.confirm) {
                            this.imgId.splice(index, 1);
                            this.imgUrl.splice(index, 1);
                        } else if (res.cancel) {
                            
                        }
                    }
                });
            },
        }
    };
</script>

<style lang="scss">
    page{
        background-color: #f5f5f5;
    }
    .content{
        padding: 20rpx;
    }
    .box{
        padding: 0 20rpx;
        background-color: #fff;
        border-radius: 20rpx;
    }
    .item{
        border-bottom: 2rpx solid #e6e6e6;
        padding: 30rpx 0;
    }
    .item:last-child{
        border-bottom: none;
        padding-bottom: 10rpx;
    }
    .title{
        padding-bottom: 15rpx;
    }
    textarea{
        width: 94%;
        padding: 20rpx;
        background-color: #fafafa;
    }
    .tit-t{
        min-height: 100rpx;
    }
    // .img-box{
    //     display: flex;
    //     flex-wrap: wrap;
    //     justify-content: flex-start;
    //     align-items: center;
    //     position: relative;
    // }
    .up-photo{
        width: 168rpx;
        height: 168rpx;
        border-radius: 15rpx;
        margin-right: 20rpx;
        margin-bottom: 20rpx;
    }
    
    .img-box{
        display: flex;
        flex-wrap: wrap;
        justify-content: flex-start;
        align-items: center;
    }
    .img-box-item{
        position: relative;
    }
    .del-img{
        font-size: 24rpx;
        color: #fff;
        padding: 5rpx 8rpx;
        background: rgba(0,0,0, .5);
        position: absolute;
        right: 15rpx;
        bottom: 15rpx;
    }
    .up-img{
        width: 149rpx;
        height: 145rpx;
        margin-right: 14rpx;
        margin-bottom: 14rpx;
    }
    .btn{
        font-size: 34rpx;
        color: #fff;
        text-align: center;
        background-color: #00a1e9;
        padding: 25rpx;
        border-radius: 50rpx;
        margin: 50rpx 0;
    }
    
    
    
</style>
